<template>
	<view class="Recharge_content Transfer_content">
		<view class="kuang">
			<view class="title">
				<view class="inline-block left">
					<image src="../../static/image/left.png" mode="" @tap="back"></image>
				</view>
			</view>
			<view class="vote_title">
				<image src="../../static/image/node_icon.png"></image>
				<text>{{i18n.jdvotetitle}}</text>
			</view>
			<view class="cuttent_vote">
				{{i18n.cuttentvote}}<text>{{curEpoch}}</text>{{i18n.cuttentvotetext}}
			</view>
			<view class="choice" :style="i18n.nodechoice">
				<text :style="i18n.choicestyle">{{i18n.candidate}}</text>
				<view class="picker" >
					<picker @change="bindPickerChange" :value="index" :range="candidateList" style="color: rgba(134, 135, 163, 1);">
							<view class="uni-input">{{candidateList[index]}}</view>
					</picker>
					<image src="../../static/image/bottom.png" class="down" style="width: 24upx;height: 12upx;margin-left: 15upx;"></image>
				</view>
			</view>
			<view class="choice" :style="i18n.nodechoice">
				<text  :style="i18n.choicestyle">{{i18n.votesamount}}</text>
				<input type="text" value="" v-model="voteStake" :placeholder="i18n.choice1placeholder + accountMaxStake" class="vote_num" :style="i18n.vote_num" placeholder-style="font-size:12px;color:rgba(134, 135, 163, 1)" style="color: rgba(134, 135, 163, 1);"/>
			</view>
			<text style="font-size: 20upx;color:#ee3f4d;padding-left: 20upx;">*{{i18n.jdtpps}}</text>
			<image :src="i18n.tpimg" class="vote_btn"  @tap="startVote"></image>
			<view class="vote_encourage">
				<text  @tap="vote_candidate">{{i18n.votingcandidate}}</text>
				<text  @tap="withdraw_candidate" v-show="showWithdraw">{{i18n.minercourage}}</text>
				<text  @tap="vote_encourage">{{i18n.voteencourage2}}</text>
			</view>
			
			<view class="candidate">
				{{i18n.candidate}}
			</view>
			
			<scroll-view scroll-y="true" class="data_list" >
				<view v-if="validCandidates.length > 0">
					<view class="item" v-for="(candidate, index) in validCandidates" :key="index">
						<view class="account">
							<text>{{candidate.name}}:</text>
							<text style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align: right;">   {{candidate.info}}</text>
						</view>
						<view class="item_detail" >
							<view class="detail_left">
								<image src="../../static/image/item_img.png"></image>
								<view class="left_right" >
									<view>{{i18n.collateralvotes}}：<text>{{candidate.quantity}} OEX</text></view>
									<view>{{i18n.currentbgr}}：<text>{{candidate.totalQuantity - candidate.quantity}} OEX</text></view>
								</view>
							</view>
							<view class="left_right">
								<view>{{i18n.totalvotes}}：<text>{{candidate.actualCounter}}</text></view>
								<view>{{i18n.myvotes}}：<text>{{candidate.reward}}</text></view>
							</view>
						</view>
					</view>
				</view>
				
				
			</scroll-view>
			
		</view>
		<password v-if="show" :gasPrice="100" :gasLimit="1000000" @close="close" @callback="callback" :yzpassword="i18n.yzpassword" :btnl="i18n.btn1" :btnr="i18n.btn2" :placeholder="i18n.placeholder" :passprice="i18n.passprice" :pwdtitle="i18n.pwdtitle"></password>
	</view>
</template>

<script>
	
	import * as oexWeb3 from 'oex-web3';
	import password from '../../components/password/password.vue';
	import BigNumber from 'bignumber.js';
	
	export default {
		computed: {
			i18n() {
				return this.$t('user')
			}
		},
		data() {
			return {
				myAccount: "", 
				candidateList: [],
				index: 0,
				curEpoch: 0,
				dposInfo: null,
				accountMaxStake: 0,
				validCandidates: [],
				show: false,
				voteStake: null,
				accountName:"",
				showWithdraw: false,
				restWithdrawValue: 0,
				isVoteAction: true,
				curAccountCandidate: null,
			}
		},
		onLoad() {
			console.log(this.accountMaxStake)
			const _this = this;
			const accountInfo = uni.getStorageSync("account_info");
			const accountName = accountInfo.accountName;
			this.accountName =  accountInfo.accountName;
			this.$Web3Wrapper.getCurrentBlock(false).then(block => {
				this.$Web3Wrapper.getEpochByHeight(block.number).then(epoch => {
					this.curEpoch = epoch;
				});
			});
			this.candidateList = [];
			// 获取所有候选者，包括正在出块的以及新注册的候选者
			this.$Web3Wrapper.getCandidates(0, true).then(candidates => {
				const candidateMap = {};
				candidates.map(candidateInfo => {
					this.candidateList.push(candidateInfo.name);
					candidateInfo.reward = new BigNumber(candidateInfo.reward).shiftedBy(18 * -1).toNumber();
					this.validCandidates.push(candidateInfo);
				});
			});
			this.$Web3Wrapper.getDposInfo().then(dposInfo => {
				this.dposInfo = dposInfo;
				const unitStake = new BigNumber(dposInfo.unitStake);
				_this.$Web3Wrapper.getAvailableStake(0, accountName).then(stake => {
					_this.getAccountMaxStake(stake,unitStake);
				}).catch(err =>{
					console.log(err)
				});
			});
			this.$Web3Wrapper.getCandidate(0, accountName).then(candidate => {
				console.log(candidate)
				if (candidate == null) {
					this.showWithdraw = false;
					return;
				}
				this.curAccountCandidate = candidate;
				this.showWithdraw = true;
				return;
			});
		},
		methods: {
			vote_candidate(){
				this.$CommonJS.navigateTo('./register_candidate');
			},
			bindPickerChange: function(e) {
					console.log('picker发送选择改变，携带值为', e.target.value)
					this.index = e.target.value
			},
			getAccountMaxStake(stake,unitStake){
				const _this = this;
				this.$Web3Wrapper.getChainConfig().then(chainConfig => {
					oexWeb3.oex.setChainConfig(chainConfig);
					_this.accountMaxStake = new BigNumber(stake).shiftedBy(chainConfig.sysTokenDecimal * -1).dividedBy(unitStake).toNumber();
				})
			},
			back(){
				this.$CommonJS.navigateBack()
			},
			close() {
				this.show = false;
			},
			vote_encourage(){
				this.$CommonJS.navigateTo('./vote_encourage')
			},
			startVote() {
				const _this=this
				this.$Web3Wrapper.getSnapShotStake(0, this.candidateList[this.index]).then(stake => {
					if (this.dposInfo.candidateAvailableMinQuantity > stake) {
						this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '当前候选人因快照金额不足，无法被投票':'The current candidate cannot be voted due to insufficient snapshot amount');
						return;
					}
					if (this.voteStake == null) {
						this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '请输入投票数量':'Please input the number of votes');
						return;
					}
					if (this.voteStake > this.accountMaxStake) {
						this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '您已超过投票限额，请调整票数':'You have exceeded the voting limit, please adjust the number of votes');
						return;
					}
					this.isVoteAction = true;
					this.show = true;
				});
			},
			withdraw_candidate() {
				const _this = this;
				const totalReward = new BigNumber(this.curAccountCandidate.reward);
				this.$Web3Wrapper.getCandidateWithdrawed(this.accountName).then(withdrawedReward => {
					withdrawedReward = new BigNumber(withdrawedReward);
					this.restWithdrawValue = totalReward.minus(withdrawedReward);
					if (this.restWithdrawValue.comparedTo(new BigNumber(0)) > 0) {
						const oexValue = this.restWithdrawValue.shiftedBy(-18).toNumber();
						uni.showModal({
						    title: _this._i18n.locale == 'zh_CN' ? '提示' : "Tip",
						    content: _this._i18n.locale == 'zh_CN' ? '您当前账号' + this.accountName + '可提取挖矿奖励金额为' + oexValue + 'OEX，如需现在提取，请点击确定。'
									: 'You can withdraw ' + oexValue + ' OEX on your account ' + this.accountName,
						    success: function (res) {
						        if (res.confirm) {
						           _this.isVoteAction = false;
						           _this.show = true; 
						        }
						    }
						});
					} else {
						this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '您当前账号' + this.accountName + '无挖矿激励可提取'
												:'No reward could be withdrawed on your account:' + this.accountName);
						return;
					}
				}).catch(err =>{
					console.log(err)
				});
			},
			callback(privateKey, gasPrice, gasLimit) {
				const candidateName = this.candidateList[this.index];
				const _this = this;
				const actionInfo = {accountName: this.accountName};
				const gasInfo = {gasPrice: "0x" + gasPrice.toString(16), gasLimit: "0x" + gasLimit.toString(16)};
				if (this.isVoteAction) {
					const payloadInfo = {candidate: candidateName, stake: "0x" + new BigNumber(this.voteStake).toString(16)};
					this.$Web3Wrapper.voteCandidate(actionInfo, gasInfo, payloadInfo, privateKey, () => { _this.show = false; }, (err) => {
						_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '发生错误:':'An error occurred:' + err);
					});
				} else {
					this.$Web3Wrapper.withdrawCandidate(actionInfo, gasInfo, privateKey, () => { _this.show = false; }, (err) => {
						_this.$CommonJS.showToast(_this._i18n.locale == 'zh_CN' ? '发生错误:':'An error occurred:' + err);
					});
				}
				
			},
		}
	}
</script>

<style lang="stylus">
	@import "../../static/stylus/nodeVote/node_vote.stylus"
</style>
